<template>
  <div id="changedialog">
    <commonformdialog
      :isshowDialogs="isshowDialog"
      :isshowconfirmbtn="false"
      :dialogWidth="'42%'"
      :enterTitle="false"
      :isshowimportTitle="false"
      :dialogTitle="`换班-${dialogparams.name}`"
      @closetextDialog="closetextDialog"
      @confirmbtn="confirmbtn"
      :topHeight="'10vh'"
    >
      <!-- 表单区域 -->
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="80px">
  <el-row>
    <el-row>
      <el-col :span="24">
         <div class="title-head">
           <div class="title">当前班型</div>
         </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="班型名称" prop="title">
            <el-input :disabled='true' v-model="formData.title" placeholder="请输入班型名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-form-item label="申领类型" prop="apply_type">
            <el-input :disabled='true' v-model="formData.apply_type" placeholder="请输入申领类型" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="班型费用" prop="cost">
            <el-input :disabled='true' v-model="formData.cost" placeholder="请输入班型费用" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-form-item label="优惠金额" prop="discounts">
            <el-input  :disabled='true' v-model="formData.discounts" placeholder="请输入优惠金额" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="收费标准" prop="standard">
            <el-input :disabled='true' v-model="formData.standard" placeholder="请输入收费标准" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-form-item label="已交金额" prop="actual_cost">
            <el-input :disabled='true' v-model="formData.actual_cost" placeholder="请输入已交金额" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="title-head">
          <div class="title">换班班型</div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="换班类型" prop="hbapply_type">
          <el-select v-model="formData.hbapply_type"  placeholder="请选择新班型的申领类型" clearable :style="{ width: '100%' }"  @change="changeApplyType">
            <el-option v-for="(item, index) in hbapply_typeOption" :key="index" :label="item.title" :value="item.id"
              :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="换班班型" prop="package_id">
          <el-select v-model="formData.package_id" :disabled="formData.hbapply_type==''"  @change="changecourse" placeholder="请选择换班班型" clearable :style="{ width: '100%' }"
           >
            <el-option v-for="(item, index) in learntypeOptions" :key="index" :label="item.title" :value="item.id"
              :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
     <!-- <el-col :span="12">
        <el-row>
          <el-form-item label="换班类型" prop="hbapply_type">
           <el-select v-model="formData.hbapply_type" placeholder="请选择新班型的申领类型" clearable :style="{width: '100%'}" >
              <el-option v-for="(item, index) in hbapply_typeOption" :key="index" :label="item.title"
                :value="item.id" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-form-item label="换班班型" prop="package_id">
            <el-select v-model="formData.package_id" placeholder="请选择换班班型" clearable :style="{width: '100%'}" @change="changecourse">
              <el-option v-for="(item, index) in package_idOptions" :key="index" :label="item.title"
                :value="item.id" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-col> -->
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="班型费用" prop="hbcost">
            <el-input :disabled='true' v-model="formData.hbcost" placeholder="请输入班型费用" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-form-item label="优惠金额" prop="hbdiscounts">
            <el-input v-model="formData.hbdiscounts" placeholder="请输入优惠金额" clearable :style="{width: '100%'}" @input='hbdiscountschange'>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="交费类型" prop="pay_type">
            <el-select v-model="formData.pay_type" placeholder="请选择交费类型" clearable :style="{width: '100%'}" :disabled='true' >
              <el-option v-for="(item, index) in pay_typeOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-col>

      <el-col :span="8">

        <el-row>
          <el-form-item label="换班费用" prop="" class="hbfy">
            <el-input :disabled='true' v-model="changeclassprice<0?0-changeclassprice:changeclassprice" placeholder="请输入换班费用" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="4">
        <el-row>
          <el-form-item label-width="0" prop="hbtype" style="margin-left:10px;">
            <el-radio-group v-model="formData.hbtype" size="medium" :disabled='true'>
              <el-radio v-for="(item, index) in field141Options" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <el-row v-if="isshowprice">
          <el-col :span="24">
            <el-form-item label="费用信息" prop="">
            <ul class="moneylist" >
              <li>
                <span>标准：{{this.formData.hbcost||0}}元</span>
              </li>
              <li>
                <span>优惠：{{this.formData.hbdiscounts||0}}元</span>
              </li>
              <li >
                <span>已收：{{this.formData.actual_cost||0}}元</span>
              </li>
              <li v-if="receivable>0">
                <span>应收：{{receivable||0}}元</span>
              </li>
              <li v-if="receivable>0">
                <span style="color:rgb(71, 98, 254);">实收：{{officialprice||0}}元</span>
              </li>
              <li v-if="receivable>0">
                <span style="color:red;">欠费：{{arrearage||0}}元</span>
              </li>
              <li v-if="receivable<0">
                <span style="color:red;">应退：{{0-receivable}}元</span>
              </li>

            </ul>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isshowprice">
          <el-col :span="24" v-if="arrearage>0">
            <el-form-item label="支付方式" prop="pay_typeprice" >
              <div class="paytypearea">

                <el-input
                 v-for="(item,index) in pay_typeOption"
                 :key="index"
                  v-model="paytypeprice[item.alias]"
                  class="payTypeinput"
                  placeholder="金额"
                  :style="{ width: '20%' }"
                  @input="paypriceinput"
                >
                  <template slot="prepend">{{item.title}}</template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-form-item label="换班日期" prop="change_time">
            <el-date-picker v-model="formData.change_time" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{width: '100%'}" placeholder="请选择换班日期" clearable></el-date-picker>
          </el-form-item>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
        </el-row>
      </el-col>
    </el-row>
  </el-row>
</el-form>

    </commonformdialog>
  </div>
</template>

<script>
//引入弹窗
import commonformdialog from '@/components/commondialog/commondialog'
import { getSessionStorage } from '@/utils/accessToken'
//utils
import { isObjectvalue } from '@/utils'
//api
import { getRead } from '@/api/student'
import { readData } from '@/api/course'
import {changecourse} from '@/api/student'
export default {
  data() {
    //支付方式验证
    var validatepay = (rule, value, callback) => {
      if (!isObjectvalue(this.paytypeprice)&&this.showpaytype) {
        callback(new Error('请输入支付方式'))
      } else {
        callback()
      }
    }
    return {
      //如果已交费用大于 班型费用支付方式就隐藏
      showpaytype:true,
      //原班型id
      classId:'',
      // 支付方式
      isshowprice:true,
      //支付方式
      paytypeprice: {
        wechat: '',
        alipay:'',
        money:'',
        pos:'',
        other:'',
        transfer:''
      },
      formData: {
        title: '',
        apply_type: '',
        cost: '',
        discounts: '',
        standard: '',
        actual_cost: '',
        package_id: '',
        hbapply_type: '',
        hbcost: '',
        hbdiscounts: '',
        pay_type: '',
        hbprice: '',
        hbtype: 2,
        change_time: null,
      },
      //班型费用
      classcost:'',
      rules: {
         pay_typeprice:[
           {
             required: true,
             validator: validatepay,
             trigger: 'change'
          }
        ],
        title: [],
        apply_type: [],
        cost: [],
        discounts: [],
        standard: [{
          required: true,
          message: '请输入收费标准',
          trigger: 'blur'
        }],
        actual_cost: [{
          required: false,
          message: '请输入已交金额',
          trigger: 'blur'
        }],
        package_id: [{
          required: true,
          message: '请选择换班班型',
          trigger: 'change'
        }],
        hbapply_type: [{
          required: true,
          message: '请输入换班类型',
          trigger: 'blur'
        }],
        hbcost: [{
          required: true,
          message: '请输入班型费用',
          trigger: 'blur'
        }],
        hbdiscounts: [{
          required: false,
          message: '请输入优惠金额',
          trigger: 'blur'
        }],
        pay_type: [{
          required: true,
          message: '请输入交费类型',
          trigger: 'blur'
        }],
        hbprice: [{
          required: true,
          message: '请输入换班费用',
          trigger: 'blur'
        }],
        hbtype: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        change_time: [{
          required: true,
          message: '请选择换班日期',
          trigger: 'change'
        }],
      },
      learntypeOptions: [],
      field141Options: [{
        "label": "补交",
        "value": 1
      }, {
        "label": "退费",
        "value": 2
      }],
      pay_typeOption:[],
      hbapply_typeOption:[],
      pay_typeOptions:[
         {
          label: '全款',
          value: 1,
        },
        {
          label: '分期',
          value: 2,
        },
      ]
    }
  },
  components: {
    commonformdialog
  },
  props: {
    //是否显示弹窗
    isshowDialog: {
      type: Boolean,
      default: false,
    },
    //id
    repairId: Number,
    //弹窗参数
    dialogparams:{
      type:Object,
      default:()=>{
        return {}
      }
    }
  },
  methods: {
    //切换申领类型
    changeApplyType(e) {
      console.log(e, '111111111111111')

       this.learntypeOptions = getSessionStorage('Optionsall')['package']
      let id = e
      if (id) {
        let newOptions = [];
        this.learntypeOptions.map((item, index) => {
          if (item.apply_type.indexOf(id) != -1) {
            newOptions.push(item)
          }
        })
        this.learntypeOptions = newOptions.concat([])
      }
      let flag=false;
      this.learntypeOptions.map((item,index)=>{
        if(item.id==this.formData.package_id){
            flag=true;
        }
      })
      if(!flag){
        this.formData.package_id=''
      }

    },
    //监听输入优惠金额
    hbdiscountschange(val){
      //判断是否输入的为数字
      let regnum = /^[0-9]*$/
      if(regnum.test(parseInt(val))){
        if(parseInt(val)==0){
          this.$message.info('优惠金额不能小于0')
          this.formData.hbdiscounts = ''
        }
      }else{
        this.$message.info('请输入正确的优惠金额！')
        this.formData.hbdiscounts = ''
      }
    },
    //切换班型
    async changecourse(val){
      if(!val){
        //清空数据
        return
      }
      //根据班型id获取详情信息
      let data = await readData({id:val})
      let result = data.data.data
      this.formData.hbcost = result.cost
      //班型费用
      this.classcost = result.cost
      this.formData.pay_type = result.pay_type
      this.isshowprice = true
      //如果已交费用大于换班费用就 隐藏 支付方式
      if(this.formData.actual_cost>=this.classcost){
        //隐藏支付方式
        this.showpaytype = false
      }else{
        this.showpaytype = true
      }
    },
    //获取换班数据
    async getchangeData() {
      let params = {
        id: this.repairId,
      }
      let data = await getRead(params)
      if(data.code=='0000'){
         //获取班型id
      this.classId = data.data.package_id.value
      this.formData.apply_type =data.data.apply_type.title
      //通过班型id 获取班型数据
      let calssData = await readData({id:this.classId})

      if(calssData.code=='0000'){
        let result = calssData.data.data
      this.formData.title = result.title
      this.formData.cost = result.cost
      //优惠金额
      this.formData.discounts = data.data.discounts
      //收费标准
      this.formData.standard = this.formData.cost-this.formData.discounts
      //已交金额
      this.formData.actual_cost = data.data.actual_cost

      }

      }

    },
    //监听支付方式输入
    paypriceinput() {
      if(this.formData.actual_cost>=this.changeclassprice){
        // this.$message.info('费已缴纳完毕！')
      }
    },
    //关闭弹窗
    closetextDialog() {
      this.$refs['elForm'].resetFields()
      this.$emit('closetextDialog')
    },
    //点击确认
    confirmbtn() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return
        let params = {
          // 学员
          student_id:this.repairId,
          // 原班型
          former_course:this.classId,
          // 现班型
          present_course:this.formData.package_id,
          //换班日期
          change_time:this.formData.change_time,
          //费用类型：1-交费，2-扣费
          type:this.formData.hbtype,
          //交费金额
          cost_money:Math.abs(this.receivable),
          //优惠金额
          discounts:this.formData.hbdiscounts,
          //交费方式
          pay_type:this.paytypeprice,
          // 现班型费用
          course_cost:this.formData.hbcost
        }
        let data = await changecourse(params)
        if(data.code=='0000'){
            this.$alert('换班成功！请耐心等待审核！', '温馨提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.$emit('refreshData')
              }
            });
            // TODO 提交表单
           this.$emit('closetextDialog')
        }

      })
    },
  },
  mounted() {
    //隐藏支付方式
    this.isshowprice = false
    //获取换班数据
    this.getchangeData()
    //交费方式
    this.pay_typeOption = getSessionStorage('Options')[15]
    //获取班型选项
    this.learntypeOptions = getSessionStorage('Optionsall')['package']
    //换班类型
    this.hbapply_typeOption = getSessionStorage('Options')[1]
    console.log(this.package_idOptions)
  },
  computed:{
    //换班费用 班型费用-班型费用--已交金额-优惠金额
    changeclassprice(){
        return this.classcost - this.formData.hbdiscounts
    },
    //实收金额
    //计算实收金额
    officialprice(){
      if(Number(this.paytypeprice.wechat) + Number(this.paytypeprice.alipay)+ Number(this.paytypeprice.money)+Number(this.paytypeprice.pos)+Number(this.paytypeprice.other)+Number(this.paytypeprice.transfer)>=this.receivable){
        return this.receivable
      }else{
        if(this.formData.actual_cost>=this.changeclassprice){
          return 0
        }else{
          return Number(this.paytypeprice.wechat) + Number(this.paytypeprice.alipay)+ Number(this.paytypeprice.money)+Number(this.paytypeprice.pos)+Number(this.paytypeprice.other)+Number(this.paytypeprice.transfer)
        }

      }
    },
    //应收金额
    receivable(){
      // 标准 - 优惠 -已收
      return this.formData.hbcost - this.formData.hbdiscounts - this.formData.actual_cost
    },

    //换班费用  新班型费用 - 优惠金额 - 已交金额
    changeclassprice(){
      return this.formData.hbcost - this.formData.hbdiscounts -this.formData.actual_cost
    },
    //欠费
    arrearage(){
      return this.receivable - this.officialprice
    }
  },
  watch:{
    receivable(val){
      console.log(val)
      // 1 是补交 2是退费
      // 负数为 退费 正数为 补交
      if(val>=0){
        this.formData.hbtype = 1

      }else{
        this.formData.hbtype = 2
      }
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep {
  .el-form{
    padding-right: 19px !important;
  }
  .el-dialog__body {
    // overflow: hidden;
    height: 530px !important;
    overflow: auto;
  }
  .el-radio__label{
    padding-left: 5px;
  }
  .hbfy .el-input-group__append{
    padding: 0px 20px;
  }
  .el-radio{
    margin-right: 0px !important;
    .el-radio__label{
      // margin-right: 4px;
    }
  }
  .el-radio+.el-radio{
    margin-left: 10px;
  }
  .paytypearea .el-input__inner {
    padding-right: 15px !important;
    width: 81px;
  }
  .el-input-group__append {
    color: #999 !important;
  }
  .el-input-group__prepend {
    background-color: #f5f7fa;
    color: #909399 !important;
    vertical-align: middle;
    display: table-cell;
    position: relative;
    padding: 0 9px !important ;
    width: 1px;
    white-space: nowrap;
  }

}
.moneylist {
  // margin: 5px 0 20px 0;
  display: flex;
  // margin-left: 20px;
  li {
    margin-right: 12px;
  }
}
.payTypeinput {
  padding: 0 !important;
  margin-right: 10px;
  width: 40px !important;
  //   margin-bottom: 20px;
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
.warn{
  width: 93%;
      position: relative;
      left: 23px;
      margin-bottom: 20px;
}
.title-head {
  display: flex;
  align-items: center;
  font-size: 15px;
  margin-bottom: 20px;
  color: #333;
  font-weight: bold;
  &::before {
    content: '';
    display: block;
    width: 3px;
    height: 20px;
    background-color: #4c68ef;
    margin-right: 10px;
  }
}
</style>
